import { i18n } from '@app-nextmesh/common/utils';
import { ErrorSchema, FieldProps, RJSFSchema } from '@rjsf/utils';
import { useEffect, useState } from 'react';
import Entity from '../Forms/components/Entity';
import FormItemError from './FormItemError';

export const EntityField = ({
  id,
  schema,
  uiSchema,
  formData,
  onChange,
  onFocus,
  disabled,
  name,
  errorSchema,
}: FieldProps<string[]>) => {
  const [error, setError] = useState<string>(null);

  const validateArray = (
    formData: string[],
    schema: RJSFSchema,
    errorSchema?: ErrorSchema<string[]>,
  ) => {
    // 判断errorSchema是否是空对象
    if (errorSchema && Object.keys(errorSchema).length === 0) {
      return null;
    }
    if (
      Array.isArray(formData) &&
      (formData.length < schema.minItems || formData.some((item) => !item))
    ) {
      return i18n.t('validation.entityMinItems', { limit: schema.minItems });
    }
    return null;
  };

  useEffect(() => {
    setError(validateArray(formData, schema, errorSchema));
  }, [formData, schema, errorSchema]);

  return (
    <>
      <Entity
        disabled={disabled}
        visible={uiSchema?.['ui:options']?.visible as boolean}
        switchedOn={true}
        name={name}
        type={uiSchema.pickTypes as string[]}
        value={formData}
        assignedValues={new Set<string>()}
        onClick={() => {
          onFocus?.(id, formData);
        }}
        onChange={(value) => {
          onChange(value);
        }}
      />
      {error && <FormItemError>{error}</FormItemError>}
    </>
  );
};
